package cn.edu.njnu.opengmpback.Modeling.service;


import cn.edu.njnu.opengmpback.Modeling.dao.ComputeModelDao;
import cn.edu.njnu.opengmpback.Modeling.dao.ProjectDao;
import cn.edu.njnu.opengmpback.Modeling.entity.ComputeModel;
import cn.edu.njnu.opengmpback.Modeling.entity.DockerPackage;
import cn.edu.njnu.opengmpback.Modeling.entity.Project;
import com.alibaba.fastjson.JSONObject;
import cn.edu.njnu.opengmpback.Modeling.entity.dto.CreateComputeModelDTO;
import cn.edu.njnu.opengmpback.Modeling.utils.*;
import cn.edu.njnu.opengmpback.common.entity.FileInfo;
import cn.edu.njnu.opengmpback.common.utils.*;
import cn.edu.njnu.opengmpback.resource.dao.ModelItemDao;
import cn.edu.njnu.opengmpback.resource.dao.ResourceDataDao;
import cn.edu.njnu.opengmpback.resource.dao.UserDataDao;
import cn.edu.njnu.opengmpback.resource.entity.ModelItem;
import cn.edu.njnu.opengmpback.resource.entity.ResourceData;
import cn.edu.njnu.opengmpback.resource.entity.SubDataItem;
import cn.edu.njnu.opengmpback.resource.entity.UserData;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.util.*;

@Service
@Slf4j
public class ComputeModelService {

    @Autowired
    ComputeModelDao computeModelDao;

    @Autowired
    UserDataDao userDataDao;

    @Autowired
    ProjectDao projectDao;

    @Autowired
    ModelItemDao modelItemDao;

    @Autowired
    DockerService dockerService;

    @Value("${containerDir}")
    private String containerDir; //容器工作空间

    @Value("${workSpaceDir}")
    private String workSpaceDir; //用户可操作的位置

    @Value("${dataStoreDir}")
    private String dataStoreDir;

    @Value("${tempUploadDir}")
    private String tempUploadDir;

    @Value("${geoserver.server}")
    private String geoserverUrl;

    @Value("${staticFilePattern}")
    private String staticFilePattern;

    @Autowired
    GeoServerUtils geoServerUtils;

    @Autowired
    FTPFileTransferService fileTransferService;

    @Autowired
    private ResourceDataDao resourceDataDao;

    @Autowired
    ExecCmdUtils execCmdUtils;

    public JsonResult test(){
        String containerid = dockerService.createContainer("python39:v1", "t4rry","/home/vge/workspace","test");
        return ResultUtils.success(containerid);
    }

    public boolean createFile(String filePath, boolean isFolder){
        try {
            if (isFolder){
                File folder=new File(filePath);
                if (!folder.isDirectory()) {
                    folder.mkdir();
                }
                return true;
            }
            else {
                File file=new File(filePath);
                if (!file.isFile()) {
                    file.createNewFile();
                }
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public JsonResult CreateComputeModel(CreateComputeModelDTO createComputeModelDTO){
        try {
            Optional<Project> projectDB = projectDao.findById(createComputeModelDTO.getProjectId());
            if(!projectDB.isPresent()){
                return ResultUtils.error(-1,"项目不存在");
            }
            if(!projectDB.get().getComputeModelId().equals("")){
                return ResultUtils.error(-1,"项目已存在计算模型");
            }
            log.info(projectDB.get().getInterpreter());
            switch (projectDB.get().getInterpreter()) {
                case "Python3_9":
                    createComputeModelDTO.setPythonVersion("python39:v1");
                    break;
                case "Python3_8":
                    createComputeModelDTO.setPythonVersion("python38:latest");
                    break;
                case "Python2_7":
                    createComputeModelDTO.setPythonVersion("python27:latest");
                    break;
            }

            //创建的computeModel对象
            ComputeModel computeModel=new ComputeModel();
            //设置computeModel的属性
            BeanUtils.copyProperties(createComputeModelDTO,computeModel);
            String workDir = containerDir + createComputeModelDTO.getProjectId();   //容器工作空间位置
            computeModel.setWorkDir(workDir);
            computeModel.setIfReq(true);
            computeModel.setPyPath(workDir + '/'+"main.py");
            computeModel.setMainPyContent("");
            computeModel.setWorkflowPath(workDir + '/'+"workflow.py");
            computeModel.setWorkflow("");
            computeModel.setPackageList(new ArrayList<>());
            //创建容器
            dockerService.initEnv(computeModel.getWorkDir(),createComputeModelDTO.getProjectId());
            String containerid = dockerService.createContainer(computeModel.getPythonVersion(), computeModel.getId(),computeModel.getWorkDir(),createComputeModelDTO.getProjectId());
            computeModel.setContainerId(containerid);
            computeModel.setId(containerid);
            dockerService.startContainer(containerid);

            computeModelDao.save(computeModel);
            //项目绑定计算模型Id
            Project project = projectDB.get();
            project.setComputeModelId(computeModel.getId());
            projectDao.save(project);

            Map<String, String> requestsData = new HashMap<>();
            requestsData.put("type", "add");
            requestsData.put("name", "requests");
            requestsData.put("version", "");
            packageOperation(computeModel.getId(), requestsData);

            return ResultUtils.success(computeModel);
        } catch (BeansException e) {
            e.printStackTrace();
            return ResultUtils.error(-1,"容器创建失败");
        } catch (InterruptedException e) {
            e.printStackTrace();
            return ResultUtils.error(-1,"容器创建失败");
        }
    }

    public JsonResult OpenComputeModel(String modelId) {
        Optional<ComputeModel> computeModelDB = computeModelDao.findById(modelId);
        if (!computeModelDB.isPresent()){
            return ResultUtils.error(-1,"项目不存在");
        }
        ComputeModel computeModel = computeModelDB.get();
        //启动容器
        try {
            String containerid;
            if (computeModel.getContainerId()==null){
                containerid = dockerService.createContainer(computeModel.getPythonVersion(), computeModel.getId(),computeModel.getWorkDir(),computeModel.getProjectId());
                computeModel.setContainerId(containerid);
                computeModelDao.save(computeModel);
            }
            else {
                containerid=computeModel.getContainerId();
            }
            //容器是否在运行中？
            boolean checkstate = dockerService.checkstate(containerid);
            if (!checkstate){
                //不在运行的话就打开
                dockerService.startContainer(containerid);
            }
            return ResultUtils.success(computeModel);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtils.error(-1,"打开容器失败");
        }
    }

    public JsonResult DeleteComputeModel(String modelId) {
        Optional<ComputeModel> computeModelDB = computeModelDao.findById(modelId);
        if (!computeModelDB.isPresent()){
            return ResultUtils.error(-1,"项目不存在");
        }
        ComputeModel computeModel = computeModelDB.get();
        String computeModelPath = computeModel.getWorkDir();
        if (computeModel.getContainerId()!=null){
            String containerId=computeModel.getContainerId();
            try {
                dockerService.stopContainer(containerId);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                try {
                    dockerService.removeContainer(containerId);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        computeModelDao.deleteById(modelId);
        Project project = projectDao.findById(computeModel.getProjectId()).get();
        project.setComputeModelId("");
        projectDao.save(project);
        geoServerUtils.removeWorkspace(project.getId());
        return ResultUtils.success("删除成功");
    }

    public JsonResult RunDemo(String modelId) {
        Optional<ComputeModel> computeModelDB = computeModelDao.findById(modelId);
        if (!computeModelDB.isPresent()){
            return ResultUtils.error(-1,"项目不存在");
        }
        ComputeModel computeModel = computeModelDB.get();
        String containerId = computeModel.getContainerId();
        String projectId = computeModel.getProjectId();
        try {
            if (!dockerService.checkstate(containerId)){
                return ResultUtils.error(-1,"运行出错");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtils.error(-1,"连接出错");
        }
        String common = "python main.py";
        dockerService.runCMDInContainer(projectId, containerId, common);
        return ResultUtils.success("运行成功");
    }
    

    public JsonResult StopDemo(String modelId) {
        Optional<ComputeModel> computeModelDB = computeModelDao.findById(modelId);
        if (!computeModelDB.isPresent()){
            return ResultUtils.error(-1,"项目不存在");
        }
        ComputeModel computeModel = computeModelDB.get();
        String containerId = computeModel.getContainerId();
        String projectId = computeModel.getProjectId();

        String common = "kill -INT `pidof python`";
        dockerService.runCMDInContainer(projectId, containerId, common);
        return ResultUtils.success("已停止");
    }


    public JsonResult StopContainer(String modelId) {
        Optional<ComputeModel> computeModelDB = computeModelDao.findById(modelId);
        if (!computeModelDB.isPresent()){
            return ResultUtils.error(-1,"模型不存在");
        }
        ComputeModel computeModel = computeModelDB.get();
        String containerId = computeModel.getContainerId();
        try {
            dockerService.stopContainer(containerId);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return ResultUtils.success("容器已停止");
    }

    public List<FileInfo> getCurDirFiles(String modelId, Map postData) {
        String path = (String) postData.get("path");
        Optional<ComputeModel> computeModelDB = computeModelDao.findById(modelId);
        if (!computeModelDB.isPresent()){
            return null;
        }
        ComputeModel computeModel = computeModelDB.get();
        String containerId = computeModel.getContainerId();
        String projectId = computeModel.getProjectId();
        List<FileInfo> fileTree = new ArrayList<>();
        return dockerService.getCurDirFiles(projectId, containerId, path, fileTree);
    }

    public JsonResult newFolder(String modelId, String path, String folder) {
        Optional<ComputeModel> computeModelDB = computeModelDao.findById(modelId);
        if (!computeModelDB.isPresent()){
            return null;
        }
        ComputeModel computeModel = computeModelDB.get();
        String containerId = computeModel.getContainerId();
        String projectId = computeModel.getProjectId();
        String storagePath = path.equals("") ? folder : path + folder;
        storagePath = workSpaceDir + storagePath; //用户操作的是data文件夹
        String common = "mkdir -p " + storagePath + " && chmod 777 " + storagePath;
        dockerService.runCMDInContainer(projectId, containerId, common);
        return ResultUtils.success("新建文件夹成功");
    }

    public JsonResult deleteFiles(String modelId, Map postData) {
        List<String> filePathList = (List<String>) postData.get("files");
        String path = (String) postData.get("path");

        Optional<ComputeModel> computeModelDB = computeModelDao.findById(modelId);
        if (!computeModelDB.isPresent()){
            return null;
        }
        ComputeModel computeModel = computeModelDB.get();
        String containerId = computeModel.getContainerId();
        String projectId = computeModel.getProjectId();
        StringBuilder cmdBuilder = new StringBuilder("rm -rf");
        for (String file : filePathList) {
            cmdBuilder.append(" ").append(workSpaceDir + path + file);
        }
        dockerService.runCMDInContainer(projectId, containerId, cmdBuilder.toString());
        for (String file : filePathList) {
            int lastIndex = file.lastIndexOf(".");
            if(lastIndex == -1){
                continue;
            }
            String fileName= file.substring(0, lastIndex);
            if (StringUtils.endsWithIgnoreCase(file, ".tiff") ||
                StringUtils.endsWithIgnoreCase(file, ".tif") ||
                StringUtils.endsWithIgnoreCase(file, ".asc")) {
                geoServerUtils.removeStore(projectId, "Image", fileName);
            }else if (StringUtils.endsWithIgnoreCase(file, ".shp")) {
                geoServerUtils.removeStore(projectId, "Shape", fileName);
            }
        }
        return ResultUtils.success("删除成功");
    }

    public JsonResult saveCode(String modelId, String content) {
        Optional<ComputeModel> computeModelDB = computeModelDao.findById(modelId);
        if (!computeModelDB.isPresent()){
            return ResultUtils.error(-1,"模型不存在");
        }
        ComputeModel computeModel = computeModelDB.get();
        String projectId = computeModel.getProjectId();
        String containerId = computeModel.getContainerId();
        String folderPath = tempUploadDir + projectId;
        File folder = new File(folderPath);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        String filePath = folderPath + "/main.py";
        try {
            Files.write(Paths.get(filePath),content.getBytes(StandardCharsets.UTF_8));
            fileTransferService.transferFileToRemoteDockerContainer(
                    filePath, containerDir + projectId + "/main.py"
            );
            computeModel.setMainPyContent(content);
            computeModelDao.save(computeModel);
            return ResultUtils.success(content);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public JsonResult packageOperation(String modelId, Map postData) {
        Optional<ComputeModel> computeModelDB = computeModelDao.findById(modelId);
        if (!computeModelDB.isPresent()){
            return ResultUtils.error(-1,"模型不存在");
        }
        ComputeModel computeModel = computeModelDB.get();
        String projectId = computeModel.getProjectId();
        String containerId = computeModel.getContainerId();

        String type = (String) postData.get("type");
        String name = (String) postData.get("name");
        String version = (String) postData.get("version");
        String command = "";
        List<DockerPackage> packageList = computeModel.getPackageList();
        switch (type) {
            case "add":
                for (DockerPackage dockerPackage : packageList) {
                    if(dockerPackage.getName().equals(name)){
                        return ResultUtils.error(-1,"存在同名依赖");
                    }
                }
                if (version.equals("")) {
                    command = "pip install " + name;
                } else {
                    command = "pip install " + name + "==" + version;
                }
                DockerPackage dockerPackage = new DockerPackage();
                dockerPackage.setName(name);
                dockerPackage.setVersion(version);
                packageList.add(dockerPackage);
                break;
            case "remove":
                for (DockerPackage dockerPackage1 : packageList) {
                    if(dockerPackage1.getName().equals(name)){
                        if (version.equals("")) {
                            command = "pip uninstall " + name + " -y";
                        } else {
                            command = "pip uninstall " + name + "==" + version + " -y";
                        }
                        packageList.remove(dockerPackage1);
                        break;
                    }
                }
        }
        dockerService.runCMDInContainer(projectId, containerId, command);
        computeModel.setPackageList(packageList);
        computeModelDao.save(computeModel);
        return ResultUtils.success(packageList);
    }

    public JsonResult copyFilesToContainer(String projectId, Map postData) {
        List<String> dataItemIds = (List<String>) postData.get("dataItemIds");
        String path = (String) postData.get("path");
        List<Map<String, String>> transfer = new ArrayList<>();
        List<String> remotePaths = new ArrayList<>();
        for (String dataItemId : dataItemIds) {
            UserData userData = userDataDao.findById(dataItemId).get();
            String filePath = dataStoreDir + userData.getFileRelativePath();
            String destPaths = containerDir + projectId + "/"  + workSpaceDir + path + userData.getName();
            Map<String, String> map = new HashMap<>();
            map.put("filePath", filePath);
            map.put("destPaths", destPaths);
            transfer.add(map);
            remotePaths.add(destPaths);
        }
        try {
            fileTransferService.transferFilesToRemoteDockerContainer(transfer);
            return ResultUtils.success(remotePaths);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public JsonResult copyFilesToContainerFormResCenter(String projectId, Map postData) {
        String resourceDataId = (String) postData.get("resourceDataId");
        List<String> dataItemIds = (List<String>) postData.get("dataItemIds");
        String path = (String) postData.get("path");
        List<Map<String, String>> transfer = new ArrayList<>();
        List<String> remotePaths = new ArrayList<>();
        ResourceData resourceData = resourceDataDao.findById(resourceDataId).get();
        List<SubDataItem> subDataItems = resourceData.getSubDataItems();
        for (String dataItemId : dataItemIds) {
            for (SubDataItem subDataItem : subDataItems) {
                if(subDataItem.getId().equals(dataItemId)){
                    String filePath = dataStoreDir + subDataItem.getFileRelativePath();
                    String destPaths = containerDir + projectId + "/"  + workSpaceDir + path + subDataItem.getName();
                    Map<String, String> map = new HashMap<>();
                    map.put("filePath", filePath);
                    map.put("destPaths", destPaths);
                    transfer.add(map);
                    remotePaths.add(destPaths);
                }
            }
        }
        try {
            fileTransferService.transferFilesToRemoteDockerContainer(transfer);
            return ResultUtils.success(remotePaths);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public JsonResult copyFilesToLocal(String modelId, Map postData) {
        List<String> filePaths = (List<String>) postData.get("filePaths");  //绝对路径数组
        Optional<ComputeModel> computeModelDB = computeModelDao.findById(modelId);
        if (!computeModelDB.isPresent()){
            return ResultUtils.error(-1,"模型不存在");
        }
        ComputeModel computeModel = computeModelDB.get();
        String projectId = computeModel.getProjectId();
        String containerId = computeModel.getContainerId();

        String localFileDir= tempUploadDir + projectId;
        File folder = new File(localFileDir);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        try {
            return ResultUtils.success(fileTransferService.transferFilesToLocal(filePaths, localFileDir));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public JsonResult getModelItems(String modelId) {
        Optional<ComputeModel> computeModelDB = computeModelDao.findById(modelId);
        if (!computeModelDB.isPresent()){
            return ResultUtils.error(-1,"模型不存在");
        }
        ComputeModel computeModel = computeModelDB.get();
        List<String> modelList = computeModel.getModelList();
        List<ModelItem> result = new ArrayList<>();
//        List<ProcessedModelItem> result = new ArrayList<>();
        for (String mid : modelList) {
            Optional<ModelItem> modelItem = modelItemDao.findById(mid);
            if (modelItem.isPresent()){

//                ModelItem tmpModelItem = modelItem.get();
//                ProcessedModelItem processedModelItem = new ProcessedModelItem();
//                processedModelItem.setId(tmpModelItem.getId());
//                processedModelItem.setName(tmpModelItem.getName());
//                processedModelItem.setAuthor(tmpModelItem.getAuthor());
//                processedModelItem.setDescription(tmpModelItem.getDescription());
//                if (Objects.equals(modelItem.get().getModelType(), "model") && modelItem.get().getData() == null){
//                    // 在这里解析model的mdlJSON
//                    ObjectMapper mapper = new ObjectMapper();
//                    try {
//                        LinkedHashMap<String, Object> mdlJsonMap = (LinkedHashMap<String, Object>) modelItem.get().getMdlJson();
////                    String jsonString = mapper.writeValueAsString(mdlJsonMap);
////                    log.info("MdlJson Class: " + tmpModelItem.getMdlJson().getClass().getName());
//                        JsonNode MdlJson = mapper.readTree(mapper.writeValueAsString(mdlJsonMap));
//                        JsonNode Mdl = MdlJson.get("mdl");
//                        JsonNode states = Mdl.get("states");
//                        ModelItemData modelItemData = getModelItemData(states);
//                        modelItem.get().setData(modelItemData);
//                    }
//                    catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
                result.add(modelItem.get());
//                result.add(processedModelItem);
            }
        }
//        log.info(result.toString());
        return ResultUtils.success(result);
    }

    public JsonResult previewFile(String projectId, Map postData) {
        try {
            String filePath = (String) postData.get("filePath");  //绝对路径
            String type = filePath.substring(filePath.lastIndexOf(".") + 1);
            String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
            String content = "";
            String previewType = "";
            String layerName = "";
            switch (type) {
                case "tiff":
                case "tif":
                    previewType = "map";
                    geoServerUtils.PublishTiff(projectId, fileName.split(".tif")[0], fileName.split(".tif")[0], null, filePath);
                    content = MessageFormat.format("{0}/{1}/wms", geoserverUrl, projectId);
                    layerName = projectId + ":" + fileName.split(".tif")[0];
                    break;
                case "shp":
                    previewType = "map";
                    geoServerUtils.PublishShape(projectId, fileName.split(".shp")[0], fileName.split(".shp")[0], null, filePath);
                    content = MessageFormat.format("{0}/{1}/wms", geoserverUrl, projectId, fileName);
                    layerName = projectId + ":" + fileName.split(".shp")[0];
                    break;
                case "txt":
                case "csv":
                case "json":
                case "xlsx":
                case "xls":
                case "doc":
                case "docx":
                    previewType = "txt";
                    List<String> txtPaths = new ArrayList<>();
                    txtPaths.add(filePath);
                    String localFileDir1 = tempUploadDir + projectId;
                    fileTransferService.transferFilesToLocal(txtPaths, localFileDir1);
                    String localFilePath = localFileDir1 + "/" + fileName;
                    try {
                        if(type.equals("xlsx") || type.equals("xls")){
                            content = previewUtils.previewExcelFile(localFilePath);
                        } else if(type.equals("csv")){
                            content = previewUtils.previewCsvFile(localFilePath);
                        } else if(type.equals("doc") || type.equals("docx")){
                            content = previewUtils.previewDocFile(localFilePath);
                        } else {
                            content = previewUtils.previewTxtFile(localFilePath);
                        }
                    } catch (IOException e) {
                        return ResultUtils.error(-1, e.getMessage());
                    }
                    break;
                case "jpg":
                case "png":
                case "webp":
                case "gif":
                case "geojson":
                    previewType = "image";
                    List<String> imgPaths = new ArrayList<>();
                    imgPaths.add(filePath);
                    String localFileDir2 = tempUploadDir + projectId;
                    fileTransferService.transferFilesToLocal(imgPaths, localFileDir2);
                    content = staticFilePattern + "/temp/" + projectId + "/" + fileName;
            }
            if(!previewType.equals("")){
                JSONObject result = new JSONObject();
                result.put("content", content);
                if(!layerName.equals("")){
                    result.put("layers", layerName);
                }
                result.put("type", previewType);
                result.put("fileName", fileName);
                result.put("absolutePath", filePath);
                return ResultUtils.success(result);
            }
            return ResultUtils.error(-1,"不支持预览格式");
        }catch (Exception e){
            log.error(e.getMessage());
            return ResultUtils.error(-1, e.getMessage());
        }
    }

    public JsonResult removeModelItem(String modelId, Map postData) {
        List<String> modelItems = (List<String>) postData.get("modelItems");
        Optional<ComputeModel> computeModelDB = computeModelDao.findById(modelId);
        if (!computeModelDB.isPresent()){
            return ResultUtils.error(-1,"模型不存在");
        }
        ComputeModel computeModel = computeModelDB.get();
        List<String> modelList = computeModel.getModelList();
        modelList.removeAll(modelItems);
        computeModel.setModelList(modelList);
        computeModelDao.save(computeModel);
        return ResultUtils.success();
    }

    public JsonResult saveWorkFlow(String modelId, Map postData) {
        String workflow= (String) postData.get("workflow");
        String py = (String) postData.get("py");
        Optional<ComputeModel> computeModelDB = computeModelDao.findById(modelId);
        if (!computeModelDB.isPresent()){
            return ResultUtils.error(-1,"模型不存在");
        }
        ComputeModel computeModel = computeModelDB.get();
        String projectId = computeModel.getProjectId();
        String containerId = computeModel.getContainerId();
        String folderPath = tempUploadDir + projectId;
        File folder = new File(folderPath);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        String filePath = folderPath + "/workflow.py";
        try {
            Files.write(Paths.get(filePath),py.getBytes(StandardCharsets.UTF_8));
            fileTransferService.transferFileToRemoteDockerContainer(
                    filePath, containerDir + projectId + "/workflow.py"
            );
            computeModel.setWorkflow(workflow);
            computeModelDao.save(computeModel);
            return ResultUtils.success(workflow);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public JsonResult runWorkFlow(String modelId) {
        Optional<ComputeModel> computeModelDB = computeModelDao.findById(modelId);
        if (!computeModelDB.isPresent()){
            return ResultUtils.error(-1,"项目不存在");
        }
        ComputeModel computeModel = computeModelDB.get();
        String containerId = computeModel.getContainerId();
        String projectId = computeModel.getProjectId();
        try {
            if (!dockerService.checkstate(containerId)){
                return ResultUtils.error(-1,"运行出错");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtils.error(-1,"连接出错");
        }
        String common = "python workflow.py";
        dockerService.runCMDInContainer(projectId, containerId, common);
        return ResultUtils.success("运行成功");
    }
}
